package app.pool.server;

import app.pool.storage.EntryInfo;
import app.pool.storage.FileData;
import app.pool.storage.StorageMethods;
import app.pool.utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RequestMapping(value = "/files")
@Controller
public class FilesController {

    private static Logger logger = LoggerFactory.getLogger(App.class);

    @GetMapping("")
    @ResponseBody
    public List<String> list(HttpServletRequest request) throws IOException {
        String[] fileNames = StorageMethods.listFileNames();
        return Utils.map(Arrays.asList(fileNames), e -> e);
    }

    @GetMapping("/{name}")
    @ResponseBody
    public void downloadBypath(@PathVariable String name, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Utils.assertNotEmpty(name);

        File destFile = StorageMethods.appFile(name);

        response.addHeader("Content-Length", destFile.length() + "");

        try (FileInputStream in = new FileInputStream(destFile)) {
            Utils.downloadAndEncodeFileName(in, request, response, name);
        }
    }

    @PostMapping("/diff")
    @ResponseBody
    public Object difffile(@RequestBody List<EntryInfo> entryInfos, HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<EntryInfo> ret = new ArrayList<>();
        for (EntryInfo entryInfo : entryInfos) {
            if(StorageMethods.existEntry(entryInfo)){
                ret.add(entryInfo);
            }
        }
        return ret;
    }

    @PostMapping("/upload")
    @ResponseBody
    public String uploadfile(FileData fileData, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Utils.assertNotNull(fileData.getFile());
        StorageMethods.storeFile(fileData);
        return "ok";
    }

}

